"""
    @Author  ：思念
    @File    ：1、基础语法.md
    @Date    ：2024/12/16 20:46
"""
from pymongo import MongoClient


# 1. 连接到 MongoDB
client = MongoClient('mongodb://localhost:27017/')
# client = MongoClient('localhost', 27017)

# 2. 选择或创建数据库
db = client['person']

# 3. 选择或创建集合
collection = db['users']

# 4. 插入数据
# 插入单个文档
# collection.insert_one({"name": "Alice", "age": 25, "status": "active"})

# 插入多个文档
# collection.insert_many([
#     {"name": "Bob", "age": 30, "status": "inactive"},
#     {"name": "Charlie", "age": 35, "status": "active"}
# ])

# # 5. 查询数据
# # 查询所有文档
print("All documents:")
for document in collection.find():
    print(document)
#
# # 查询特定条件的文档
print("\nDocuments with status 'active':")
for document in collection.find({"status": "active"}):
    print(document)
#
# # 使用条件操作符
print("\nDocuments with age greater than 25:")
for document in collection.find({"age": {"$gt": 25}}):
    print(document)
#
# # 6. 更新数据
# # 更新单个文档
# collection.update_one({"name": "Alice"}, {"$set": {"age": 26}})
#
# # 更新多个文档
# collection.update_many({"status": "active"}, {"$set": {"status": "very active"}})
#
# # 7. 删除数据
# # 删除单个文档
# collection.delete_one({"name": "Bob"})
#
# # 删除多个文档
# collection.delete_many({"status": "very active"})
#
# # 8. 查看剩余数据
# print("\nRemaining documents:")
# for document in collection.find():
#     print(document)
#
# # 9. 创建索引
# # 创建单字段索引
# collection.create_index([("name", 1)])
#
# # 创建复合索引
# collection.create_index([("name", 1), ("age", -1)])
#
# # 10. 聚合操作
# # 计算平均年龄
# pipeline = [
#     {"$group": {"_id": None, "averageAge": {"$avg": "$age"}}}
# ]
# result = collection.aggregate(pipeline)
# print("\nAverage Age:")
# for doc in result:
#     print(doc)
#
# # 分组统计
# pipeline = [
#     {"$group": {"_id": "$status", "count": {"$sum": 1}}}
# ]
# result = collection.aggregate(pipeline)
# print("\nGroup by Status:")
# for doc in result:
#     print(doc)

# 11. 删除集合
# collection.drop()

# 12. 关闭连接
client.close()
